package com.sinoeyes.controller.system;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletResponse;

import com.sinoeyes.common.cache.RedisCache;
import com.sinoeyes.common.constant.Constants;
import com.sinoeyes.common.result.RCode;
import com.sinoeyes.common.result.Result;
import com.sinoeyes.common.utils.IdUtils;
import com.sinoeyes.common.utils.VerifyCodeUtils;
import com.sinoeyes.common.utils.sign.Base64;
import com.sinoeyes.vo.system.CaptchaDataVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 验证码操作处理
 */
@RestController
@Api(value = "验证码操作 API", tags = {"验证码操作处理"})
public class CaptchaController
{
    @Autowired
    private RedisCache redisCache;

    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    @ApiOperation("获取验证码")
    public Result<CaptchaDataVo> getCode(HttpServletResponse response) throws IOException
    {
        // 生成随机字串
        String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
        // 唯一标识
        String uuid = IdUtils.simpleUUID();
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;

        redisCache.setCacheObject(verifyKey, verifyCode, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        // 生成图片
        int w = 111, h = 36;
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        VerifyCodeUtils.outputImage(w, h, stream, verifyCode);
        try {
            CaptchaDataVo captchaDataVo = new CaptchaDataVo();
            captchaDataVo.setUuid(uuid);
            captchaDataVo.setImg(Base64.encode(stream.toByteArray()));
            return Result.success(captchaDataVo);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failure(RCode.FAILURE);
        } finally {
            stream.close();
        }
    }
}
